package com.example.demo.nio.chat_room.client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

public class ClientStart{

    private String name;

    public ClientStart(String name) {
        this.name = name;
    }

    public void client() {
        try {
            // 初始连接
            SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 7000));
            socketChannel.configureBlocking(false);
            Selector selector = Selector.open();
            socketChannel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_WRITE | SelectionKey.OP_READ);

            // 开一个阻塞线程去发数据,不会影响到这里的选择器轮询
            new Thread(new ClientThread(name, socketChannel)).start();

            // 处理事件
            while (true) {
                selector.select();
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    keyHandler(key);
                    iterator.remove();
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 事件处理器
     * @param key 事件标记
     */
    private void keyHandler(SelectionKey key) {
        // 读取数据
        if (key.isReadable()) {
            SocketChannel channel = (SocketChannel) key.channel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            try {
                // 这里就直接拿了（不比服务端的操作）
                int len = channel.read(byteBuffer);
                if(len==-1){
                    // 清理内容
                    key.selector().close();
                    // 如果后续有主动关闭操作则这里关闭通道会是第二次执行
                    // 但是没关系,即使第二次也会被忽略什么都不会做
                    channel.close();
                    System.out.println("客户端关闭！");
                    System.exit(0);
                } else if(len>0){
                    System.out.println(new String(byteBuffer.array(), 0, len, StandardCharsets.UTF_8));
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
